package com.guomw.report.web.controller;

import com.guomw.report.common.config.Constant;
import com.guomw.report.common.enums.AppCode;
import com.guomw.report.common.utils.ApiResult;
import com.guomw.report.service.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileService fileService;

    @RequestMapping("/uploadfolder")
    public String uploadfolder(Model model) {
        model.addAttribute("checked", "/file/uploadfile/" + Constant.CHECKED);
        model.addAttribute("chain", "/file/uploadfile/" + Constant.CHAIN);
        return "file/uploadfolder";
    }

    @RequestMapping("/uploadfile/{folder}")
    public String uploadfile(@PathVariable(name = "folder") String folder, Model model) {
        model.addAttribute("folder", folder);
        return "file/uploadfile";
    }


    @RequestMapping("/list")
    @ResponseBody
    public ApiResult list(String folder,
                          @RequestParam(required = false, defaultValue = "") String name,
                          @RequestParam(required = false, defaultValue = "1") Integer pageIndex) {

        return ApiResult.resultWith(AppCode.SUCCESS, fileService.searchList(folder, name, pageIndex));
    }

    @RequestMapping("/delete")
    @ResponseBody
    public ApiResult delete(String folder, String name) {
        fileService.delete(folder, name);
        return ApiResult.resultWith(AppCode.SUCCESS);
    }

    @RequestMapping("/deleteAll")
    @ResponseBody
    public ApiResult deleteAll(String folder, String names) {
        for (String name : names.split(",")) {
            if (!StringUtils.isEmpty(name)) fileService.delete(folder, name);
        }
        return ApiResult.resultWith(AppCode.SUCCESS);
    }
}
